using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using System.IO;
using GuavaLib;
using GuavaData;
using System.Reflection;

namespace GuavaTestBed
{
    public partial class QueryInterface : UserControl
    {
        GQueryNode rn;
        List<string> properties;
        
        public QueryInterface()
        {
            InitializeComponent();
            properties = new List<string>();
            PropertyInfo[] props = typeof(Guava).GetProperties();
            foreach (PropertyInfo p in props)
            {
                if (p.Name[0] == 'G')
                {
                    properties.Add(p.Name);
                }
            }
        }
        
        public void Init(GTree gt)
        {
            rn = gt.ToBuildTree();
            this.trvQuery.Nodes.Add(rn);
            cboMethod.SelectedIndex = 0;
        }

        private void trvQuery_AfterSelect(object sender, TreeViewEventArgs e)
        {
            GQueryNode qn = trvQuery.SelectedNode as GQueryNode;
            if (qn.g.GDomain != null)
            {
                GuavaViewer gv = new GuavaViewer(qn);
                gv.ShowDialog();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {

            if (String.IsNullOrEmpty(txtParameter.Text))
                MessageBox.Show("Search Parameter cannot be empty");
            else
            {
                rn.TraverseNSetNodes(trvQuery, 'C'); //reset the tree
                rn.TraverseNFindNodes(trvQuery, txtParameter.Text, cboMethod.SelectedItem.ToString());
                rn.TraverseNSetNodes(trvQuery, 'S'); //find the fullpath of found nodes and expand      
            }
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            rn.ResetGTreeView(trvQuery);
        }

        private void btnQuery_Click(object sender, EventArgs e)
        {
            try
            {
                // Build the query transaction
                Command c = GQueryNode.toQuery(trvQuery);
                DataSet dout = AppData.c.PoseQueryCommand(c);
                
                dgvResults.DataSource = dout.Tables[0];
                this.lblRows.Text = dout.Tables[0].Rows.Count.ToString();
                if (this.chkSaveQuery.Checked)
                {
                    SaveQryResultsToFile(dout);
                }
            }
            catch (Exception err)
            {
                MessageBox.Show(err.Message);
            }
        }

        public void SaveQryResultsToFile(DataSet ds)
        {

            SaveFileDialog sfdQryResult = new SaveFileDialog();
            string path = @"c:\temp";
            sfdQryResult.InitialDirectory = path;

            sfdQryResult.Title = "Save query results to file";
            sfdQryResult.Filter = "Comma seperated valus (*.csv)|*.csv";
            sfdQryResult.FilterIndex = 2;
            sfdQryResult.RestoreDirectory = true;
            sfdQryResult.CreatePrompt = true;
            sfdQryResult.OverwritePrompt = false;

            MessageBox.Show(sfdQryResult.FileName);
            if (sfdQryResult.ShowDialog() == DialogResult.OK)
            {
                // Create a stream writer to append text to an existing file.
                if (File.Exists(sfdQryResult.FileName))
                {
                    DialogResult result = MessageBox.Show("Do you want to overwrite an existing file ?",
                        "Save query results to file", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                        using (StreamWriter sw = File.CreateText(sfdQryResult.FileName))
                            WriteToFile(sw, ds);
                    else
                        using (StreamWriter sw = File.AppendText(sfdQryResult.FileName))
                            WriteToFile(sw, ds);
                }

                else
                    using (StreamWriter sw = File.CreateText(sfdQryResult.FileName))
                        WriteToFile(sw, ds);
            }
        }


        private void WriteToFile(StreamWriter sw, DataSet ds)
        {
            foreach (DataColumn dc in ds.Tables[0].Columns)
            {
                sw.Write(dc.ColumnName + ",");
            }
            sw.WriteLine();
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
                    sw.Write(dr[i].ToString() + ",");
                sw.WriteLine();
            }
            sw.Close();
        }

        private void btnCreateClassifiers_Click(object sender, EventArgs e)
        {
            ClassifierBuilder cb = new ClassifierBuilder(rn.ToQueryOutputScheme());
            if (cb.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    // Build the query transaction
                    Command c = GQueryNode.toQuery(trvQuery);
                    DataSet dout = Classifier.ApplyClassifiers(cb.lcw, AppData.c.PoseQueryCommand(c));
                    dgvResults.DataSource = dout.Tables[0];
                    this.lblRows.Text = dout.Tables[0].Rows.Count.ToString();
                    if (this.chkSaveQuery.Checked)
                    {
                        SaveQryResultsToFile(dout);
                    }
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message);
                }
            }
        }
    
        
    }
}
